<?php
/**
 * 孵化器预约模型类
 */

class IncubatorOrderModel extends Model
{

    const VISIT = 1; //参观
    const STAY = 2; //入住




    public function IncubatorOrderModel()
    {
        parent::__construct('incubator_order');

    }

    // public $order_status_arr=array(
    //     '0'=> '预约中',
    //     '1'=> '已赴约',
    //     '2'=> '已取消',
    //     '3'=> '未赴约',
    // );

    public $order_status_arr=array(
        '0'=> '预约中',
        '1'=> '预约成功',
        '2'=> '预约失败',
    );

    //单条信息
    public function getIncubatorOrderInfo($where, $fields = '')
    {
        return $this->field($fields)->where($where)->find();
    }
    //获取列表
    public function getIncubatorOrderList($fields = '', $where = '', $orderby = '', $groupby = '')
    {
        return $this->field($fields)->where($where)->group($groupby)->order($orderby)->limit()->select();
    }


    //获取园区和众创空间预约的入住和参观
    public function getIncubatorOrder($where='',$orderby=''){

        $data = M('incubator as a')->join('tp_incubator_order as b on b.incubator_id = a.incubator_id')->where($where)->order($orderby)->select();
//        dump($data);
//        dump(M('tp_incubator as a')->getLastSql());die;
        return $data;
//"SELECT * FROM tp_incubator AS a INNER JOIN tp_incubator_order AS b ON a.incubator_id = b.incubator_id WHERE a.incubator_type = 2 and b.order_type = 2";


    }

    //连表获取总量
    public function getIncubatorJoinOrderNum($where='')
    {
        $count = M('incubator as a')->join('tp_incubator_order as b on b.incubator_id = a.incubator_id')->where($where)->count();
        return $count;
    }

    //获取数量
    public function getIncubatorOrderNum($where='')
    {
        $count = $this->where($where)->count();
        return $count;
    }
    //增加预约
    public function addIncubatorOrder($arr){
        return $this->add($arr);
    }
    //删除预约
    public function delIncubatorOrder($order_id){
        return $this->where('order_id='.$order_id)->delete();
    }
    //编辑预约
    public function editIncubatorOrder($order_id,$arr){
        return $this->where('order_id='.$order_id)->save($arr);
    }



    //数字转文字
    public function numDigitalText($status){

        return $this->order_status_arr[$status];
    }

    public function payStatus(){
        return array(
          '0' => '待支付',
          '1' => '已完成',
          '2' => '已取消',
          '3' => '已退款',
        );
    }


    public function getListData($incubator_order_list){

        $incubator_obj = new IncubatorModel();
        foreach ($incubator_order_list as $k=>$v){
            $incubator_info = $incubator_obj->getIncubatorInfo('incubator_id='.$v['incubator_id']);
            //孵化器名字
            $incubator_order_list[$k]['incubator_name']=$incubator_info['incubator_name'];

            //预约状态
//            $incubator_order_list[$k]['state']=$v['status'];
            $incubator_order_list[$k]['status']=self::numDigitalText($v['order_status']);

            //支付状态
            $pay_status = self::payStatus();
            $incubator_order_list[$k]['state'] = $pay_status[$v['pay_status']];

            //地址
            $incubator_order_list[$k]['address'] = $incubator_info['address'];

            //封面图
            $pic_arr = explode(',',$incubator_info['pic_url']);
            $incubator_order_list[$k]['pic'] =$pic_arr[0];
        }

        return $incubator_order_list;
    }


    public function setOrderState($order_id, $state){
        $order = $this->getIncubatorOrderInfo('order_id ='.$order_id);
        $incubator_obj = new IncubatorModel();
        $incubator_info = $incubator_obj ->getIncubatorInfo('incubator_id ='.$order['incubator_id']);
        if($incubator_info['incubator_type']==1){
                $type_name = '园区';
        }else{
                $type_name = '众创空间';
        }

        $order['incubator'] = $incubator_info['incubator_name'];
        $order['time'] = date('Y-m-d',$order['order_time']);
        $station_obj = new StationModel();
        $station_info = $station_obj->getStationInfo('station_type_id ='.$order['station_type'],'station_type_name');
        $order['station_name'] = $station_info['station_type_name'];
        $order['incubator_type_val']=$incubator_info['incubator_type'];

        $contents = serialize($order);
        $message_obj = new MessageModel();
        if($state == 1){
            $r = $this->editIncubatorOrder($order_id, array('order_status'=> 1));
            if($r){
                if($order['order_type'] == 1){
                    $msg = '您的预约参观'.$incubator_info['incubator_name'].$type_name.'申请已通过！请去查看！';
                    $message_type = MessageModel::VISIT;
                }else{
                    $msg = '您的预约入驻'.$incubator_info['incubator_name'].$type_name.'申请已通过！请去查看！';
                    $message_type = MessageModel::ENTER;
                }
                //消息推送
                $message_obj->addMessage($order_id, $message_type, 0, $order['user_id'], $msg, $contents);

                if($order['order_type'] == 2) {
                    //入住审核通过向客户表里插入数据
                    $customer_obj = new CustomerModel();
                    $data =array(
                        'customer_name'=>$order['company_name'],
                        'likeman'=>$order['contacts'],
                        'mobile'=>$order['contact_number'],
                        'remark'=>$order['user_remarks'],
                        'file'=>$order['prospectus'],
                        'salesman'=> 0 ,
                        'follow_state'=> 0 ,
                        'addtime'=> time() ,
                    );
                    if($incubator_info['incubator_type']==1){//园区
                        $data['lease_area'] =$order['station_num'];
                    }elseif($incubator_info['incubator_type']==2){//众创空间
                        $data['lease_station'] =$order['station_num'];
                    }
                    $customer_obj->addCustomer($data);
                }

                return true;
            }
            return false;
        }elseif($state == 2){
            $admin_remarks = I('content');
            // if(!$content) return false; 
            $r = $this->editIncubatorOrder($order_id, array('order_status'=> 2, 'admin_remarks'=> $admin_remarks));
            if($order['order_type'] == 1){
                $msg = '您的预约参观'.$incubator_info['incubator_name'].$type_name.'申请未通过！请去查看！';
                $message_type = MessageModel::VISIT;
            }else{
                $msg = '您的预约入驻'.$incubator_info['incubator_name'].$type_name.'申请未通过！请去查看！';
                $message_type = MessageModel::ENTER;
            }
            if($r){

                if($order['order_type'] == 2){
                    //退款
                }
                $message_obj->addMessage($order_id, $message_type, 0, $order['user_id'], $msg, $contents);
                return true;
            }
            return false;
            
        }
    }

    /**
     * 生成订单号
     * @author 姜伟
     * @param void
     * @return string $order_sn
     * @todo 查询当天数据库中的订单量$count，订单号即为日期 . ($count + 1)，如201403010099，2014年3月1日的第99个订单
     */
    public function generateOrderSn()
    {
        //当天0点的时间戳
        $timestamp = strtotime(date('Y-m-d', time()));
        //当天订单总量
        $count = $this->where('addtime >=' . $timestamp)->count();
        //后缀位数
        $len = strlen((string) $count);
        //少于4位取4位，否则不变
        $len = $len < 4 ? 4 : $len;
        $suffix = sprintf("%0" . $len . "d", $count);
        $order_sn = date('Ymd') . $suffix;

        return $order_sn;
    }



    //计算某天出租的某个工位的数量
    public function getTotalStationNum($where){
        return $this->where($where)->sum('station_num');
    }
}